/**
 * Copyright (C), 2017-2018, XXX有限公司
 * FileName: VelocityGenerator
 * Author:   zengjian
 * Date:     2018/8/2 15:34
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package velocity;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Properties;

/**
 * 〈自动生成代码〉<br>
 * 〈一句话描述〉
 *
 * @author zengjian
 * @create 2018/8/2 15:34
 */
public class VelocityGenerator {

    public static void main(String[] args) {

        Properties properties = new Properties();
        // 解决编码问题
        properties.put("input.encoding", "UTF-8");
        properties.put("output.encoding", "UTF-8");
        VelocityEngine ve = new VelocityEngine(properties);
        ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());

        ve.init();
        Template actionTpt = ve.getTemplate("/velocity/actionTemplate.vm");
        Template listJspTpt = ve.getTemplate("/velocity/ListJspTemplate.vm");
        //Template addTpt = ve.getTemplate( "AddTemplate.vm");
        //Template modifyTpt = ve.getTemplate("ModifyTemplate.vm");
        VelocityContext ctx = new VelocityContext();

        ctx.put("classNameLowCase", "teacher");
        ctx.put("classNameUpCase", "Teacher");
        String[][] attrs = {
                {"Integer", "id"},
                {"String", "name"},
                {"String", "serializeNo"},
                {"String", "titile "},
                {"String", "subject"}
        };
        ctx.put("attrs", attrs);
        String rootPath = "D:\\WorkJian\\git-mayun\\yinxue\\yinxue-test\\src\\main\\java\\velocity\\".replaceAll("\\\\", "/");
        merge(actionTpt, ctx, rootPath + "TeacherAction.java");
        merge(listJspTpt, ctx, rootPath + "teacherList.jsp");
        //merge(addTpt,ctx,rootPath+"/webapp/teacherAdd.jsp");
        //merge(modifyTpt,ctx,rootPath+"/webapp/teacherModify.jsp");
        System.out.println("success...");
    }

    private static void merge(Template template, VelocityContext ctx, String path) {
        PrintWriter writer = null;
        try {
            writer = new PrintWriter(path);
            template.merge(ctx, writer);
            writer.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            writer.close();
        }
    }
}